using System;
using System.Collections.Generic;
using CommandLine;

namespace ET
{

    [ActorMessageHandler]
    public class C2M_BuyItemHandler : AMActorLocationRpcHandler<Unit, C2M_BuyItemRequest, M2C_BuyItemResponse>
    {
        protected async override ETTask Run(Unit unit, C2M_BuyItemRequest request, M2C_BuyItemResponse response, Action reply)
        {
            try
            {
                ShopConfig shopConfig = ShopConfigCategory.Instance.GetShopConfigInItemConfigId(request.ItemId);
                TCharacter character = unit.GetComponent<TCharacter>();
                if (shopConfig.MoneyType == "Gem")
                {
                    if (character.Gem < shopConfig.SellPrice * request.ItemCount)
                    {
                        response.Error = ErrorCode.ERR_Error;
                        response.Message = "元宝不足";
                        reply();
                        return;
                    }
                }
                else
                {
                    if (character.Gold < shopConfig.SellPrice * request.ItemCount)
                    {
                        response.Error = ErrorCode.ERR_Error;
                        response.Message = "金币不足";
                        reply();
                        return;
                    }
                }
                
                
                BagComponent bag = unit.GetComponent<BagComponent>();
                if (bag.Items.Count + request.ItemCount > bag.CurrSize)
                {
                    response.Error = ErrorCode.ERR_Error;
                    response.Message = "背包已满";
                    reply();
                    return;
                }

                List<Item> items = bag.AddBagItem(request.ItemId, request.ItemCount);
                for (int i = 0; i < items.Count; i++)
                {
                    response.Items.Add(bag.DeserializeItem(items[i]));
                }
                
                character.Gold -= shopConfig.SellPrice * request.ItemCount;
                
                reply();
                
                
                await ETTask.CompletedTask;
            }
            catch (Exception e)
            {
                ReplyError(response,e,reply);
                throw;
            }
        }
}
}